<?php

namespace app\common\model;

use think\Cache;
use think\Model;


class Navigation extends Model
{

    // 表名
    protected $name = 'navigation';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }
    

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 获取定义的导航类别列表
     * @return array
     */
    public static function getCategoryList()
    {
        $data = config('site.navigation') ?? [];
        foreach ($data as $k => &$v) {
            $v = __($v);
        }
        return $data;
    }

    public static function getTypeList()
    {
        return ['wechat_applet' => __('Type wechat_applet')];
    }

    /**
     * 获取横幅列表
     */
    public static function getBanner()
    {
        $list = Cache::tag('api')->get('banner');
        if (!$list) {
            $list = self::where(['category' => 'banner', 'status' => 1])->order('weigh')->select();

            foreach ($list as &$v) {
                $v['icon'] = cdnurl($v['icon'], true);
                $v['image'] = cdnurl($v['image'], true);
            }

            Cache::tag('api')->set('banner', $list, 60 * 60);
        }
        return $list;
    }

    /**
     * 获取分类列表
     */
    public static function getCategory()
    {
        $list = Cache::tag('api')->get('category');
        if (!$list) {
            $list = self::where(['category' => 'category', 'status' => 1])->order('weigh')->select();
            foreach ($list as &$v) {
                $v['icon'] = cdnurl($v['icon'], true);
                $v['image'] = cdnurl($v['image'], true);
            }
            Cache::tag('api')->set('category', $list, 60 * 60);
        }
        return $list;
    }
}
